from django.shortcuts import render
from django.views import View
from ihome.libs.captcha.captcha import captcha
from ihome.libs.yuntongxun.ccp_sms import CCP
from django_redis import get_redis_connection
from django.http import JsonResponse, HttpResponse
import json, re, random


class ImageCodeView(View):
    """图片验证码"""

    def get(self, request):
        cur = request.GET.get("cur")
        pre = request.GET.get("pre", "")

        # 1、生成图形验证码
        text, image = captcha.generate_captcha()

        # 2、保存图形验证码
        redis_conn = get_redis_connection("verify_code")
        redis_conn.setex("img_%s" % cur, 300, text)
        print("图片验证码：", text)
        old_image = redis_conn.get("img_%s" % pre)
        if old_image:
            redis_conn.delete("img_%s" % pre)

        # 3、响应图形验证码: image/jpg
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    """短信验证码"""

    def post(self, request):
        # 1. 提取参数
        json_dict = json.loads(request.body.decode("utf-8"))
        mobile = json_dict.get("mobile")
        id = json_dict.get("id")
        text = json_dict.get("text")

        # 2. 校验参数
        if not all([mobile, id, text]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 4004, 'errmsg': 'mobile格式有误!'})
        # 查询redis数据库的图片验证码并对比
        redis_conn = get_redis_connection("verify_code")
        image_code = redis_conn.get("img_%s" % id)
        if image_code is None:
            return JsonResponse({'code': 4004, 'errmsg': '图形验证码失效'})
        redis_conn.delete("img_%s" % id)
        image_code = image_code.decode("utf-8")
        if image_code.lower() != text.lower():
            return JsonResponse({'code': 4004, 'errmsg': '图形验证码有误'})

        # 3、业务数据处理
        # 校验短信标志
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code': 4201, 'errmsg': '发送短信验证码频繁'})
        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        redis_conn.setex("sms_%s" % mobile, 300, sms_code)
        CCP().send_template_sms(mobile, [sms_code, 5], 1)
        print("短信验证码:", sms_code)
        # 设置短信标志
        redis_conn.setex('send_flag_%s' % mobile, 60, 1)

        # 4、构建响应
        return JsonResponse({"errno": 0, "errmsg": "发送成功"})
